
package com.link.gateway.core.utils;

import com.link.gateway.core.redis.redisclient.JedisClusterSingleton;
import com.link.gateway.core.redis.redisclient.LinkRedisClient;
import com.link.gateway.core.redis.redisclient.LinkRedisClusterClient;
import com.link.gateway.core.redis.redisclient.LinkRedisSingleClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;

public final class RedisUtil {
    private static final Logger logger = LogManager.getLogger(RedisUtil.class);

    /* jedisPool初始化超时时间 */
    private static int TIMEOUT = 1000000;


    public static LinkRedisClient getJedis() {
        LinkRedisClient redisClient;
        //是否启用redis集群
        if (YmlConstants.isApplicationRedisClusterState()) {
            redisClient = new LinkRedisClusterClient(getClusterJedis());
        } else {
            redisClient = new LinkRedisSingleClient(getSingleJedis());

        }
        return redisClient;
    }


    /**
     * 单机redis
     *
     * @return jedis对象
     */
    private static Jedis getSingleJedis() {
        int port1 = Integer.valueOf(YmlConstants.getApplicationRedisPort()).intValue();
        Jedis jedis = new Jedis(YmlConstants.getApplicationRedisHost(), port1, TIMEOUT);
        String redisPassword = YmlConstants.getApplicationRedisPassword();
        if (redisPassword != null && !redisPassword.isEmpty()) {
            jedis.auth(redisPassword);
        }
        return jedis;
    }


    /**
     * 获取redis集群redis
     *
     * @return jedis对象
     */
    private static JedisCluster getClusterJedis() {
        /*
            @update by LiYang
            @date 20190417
            注释原有获取JedisCluster对象的方法，使用新方法获取JedisCluster
         */

        JedisClusterSingleton jedisClusterSingleton = JedisClusterSingleton.getInstance();
        return jedisClusterSingleton.getJedisCluster();

    }

    public static String getCropProperty(String propertyKey, String corpId) {
        LinkRedisClient jedis = getJedis();
        String result;
        try {
            String key = "APPLICATION_PARM_" + corpId;
            result = jedis.hget(key, propertyKey);
        } finally {
            returnResource(jedis);
        }

        return result;
    }


    /**
     * 释放jedis资源
     *
     * @param jedis
     */
    public static void returnResource(LinkRedisClient jedis) {
        /*
            @update by LiYang
            @date 20190417
            添加一个判断，如果为单节点模式，执行原有returnResource方法；
            如果为集群模式，则不处理
         */
        if (!YmlConstants.isApplicationRedisClusterState()) {
            if (jedis == null) {
                return;
            }
            try {
                jedis.close();
            } catch (Exception e) {
                logger.error("jedis回收失败，" + e.getMessage());
            }
        }
    }

}
